package com.spring.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.spring.domain.Students;
import com.spring.services.Services;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

	@Autowired
	private Services services;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		return "home";
	}

	@RequestMapping(value = "/students", method = RequestMethod.GET)
	@ResponseBody
	public List<Students> listStudent() {
		return services.getListStudents();
	}

	@RequestMapping(value = "/students/{id}")
	@ResponseBody
	public Students getStudent(@PathVariable("id") int id) {
		return services.getStudent(id);
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	public String doRegister(@RequestBody Students stu) {
		if (!stu.getName().equals("") && !stu.getAddress().equals("")
				&& !stu.getGrade().equals("") && !stu.getMajor().equals("")) {
			services.saveStudent(stu);
			return "Register Successfully";
		} else {
			return "Register Failed";
		}
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	@ResponseBody
	public String deleteStudent(@PathVariable("id") int id) {
		Students student = services.getStudent(id);
		if (services.deleteStudent(student)) {
			return "Delete success";
		} else {
			return "Delete Failed";
		}
	}

	@RequestMapping(value = "/edit")
	@ResponseBody
	public String editStudent(@RequestBody Students stu) {
		System.out.println(stu.getStudentid() + stu.getName() + stu.getAge() + stu.getAddress() + stu.getGrade() + stu.getMajor());
		if (services.updateStudent(stu)) {
			return "Update Success";
		} else {
			return "Update failed";
		}
	}

}
